const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const https = require('https'); // 引入 https 模块
const fs = require('fs'); // 用来读取文件
const multer = require('multer');
const path = require('path');
const con2mysql=require('./myutilitis');

const app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(express.json());

const connection=con2mysql();//连接到mysql

const heartbeatQuery = 'INSERT INTO heartbeats (timestamp) VALUES (NOW())';

// 每隔一分钟（60000毫秒）执行一次心跳包查询
setInterval(() => {
    connection.query(heartbeatQuery, (error, results, fields) => {
        if (error) throw error;
        // 心跳包发送成功的回调逻辑
        console.log('Heartbeat sent successfully.');
    });
}, 60000);

//read newest 100 records
app.get('/', (req, res) => {
    let sql='select * from sensor_data order by timestamp desc limit 100';
    connection.query(sql, function (error, results, fields) {
        if (error){
            console.log(error);
        }
        else{
            res.json(results);
            // console.log(results);
            console.log(fields);
        }
    })
})

//select distinct router_number
app.get('/shuju', (req, res) => {
    let sql='select distinct router_number from sensor_data';
    connection.query(sql, function (error, results) {
        if (error)
            console.log(error);

        res.json(results.map(item => item.router_number))
        console.log(results)
    })
})

//select sensor data via router number
app.post('/rn', (req, res) => {
    console.log(req.body);
    console.log('request path /rn');
    const inputData = req.body.inputData;
    let sql='select timestamp,humidity,temperature,ph from sensor_data where router_number = ? AND picture_path = ? order by timestamp desc limit 100';
    connection.query(sql, [inputData, '0'], (error, results) => {
        if (error)
        {
            console.log(error);
        }
        else{
            res.json(results);
            console.log(results);
        }
    })
})

//select image filename
app.post('/img', (req, res) => {
    console.log(req.body);
    console.log('request path /img');
    const inputData = req.body.inputData;
    let sql='select picture_path from sensor_data where router_number = ? AND picture_path != ? order by timestamp desc limit 100';
    connection.query(sql, [inputData, '0'], (error, results) => {
        if (error){
            console.log(error);
        }
        else{
            res.json(results);
            console.log(results);
        }
    })
})

const upload = multer({
    dest: path.join('C:', 'picture'),
    limits: { fileSize: 3 * 1920 * 1080 },
});

app.use('/uploads', express.static(path.join('C:', 'picture')));

app.post('/upload', upload.single('image', (req, res) => {
    if (!req.file) {
        return res.status(400).send('no file upload');
    }
    else
    {
        const imageUrl = `https://kaopu328.site/uploads/${req.file.filename}`;
        res.json({ imageUrl });
    }
}));

const sslOptions = {
    key: fs.readFileSync(__dirname + '/kaopu328.site.key'), // 私钥
    cert: fs.readFileSync(__dirname + '/kaopu328.site_bundle.crt'), // 证书文件    
};

const PORT = 3000;
https.createServer(sslOptions, app).listen(PORT, '0.0.0.0', () => {
    console.log(`HTTPS server is running on https://124.220.108.105:${PORT}`);
});